<template>
	<!-- 发布页的表单组件 -->
	<view class="formcontent">
		<uni-forms ref="baseForm" validate-trigger="bind" label-align="left" label-width="80" :border="true" :modelValue="baseFormData" :rules="rules">
			<uni-forms-item  label="姓名:" name="contract"  required>
				<input   @blur="binddata('contract', $event.detail.value)" v-model="baseFormData.contract"  />
			</uni-forms-item>
			<uni-forms-item label="联系方式:" name="tel" required>
				<input  @blur="binddata('tel', $event.detail.value)"  v-model="baseFormData.tel" />
			</uni-forms-item>
			<uni-forms-item label="房源标题:" name="title" required>
				<input  @blur="binddata('title', $event.detail.value)" :inputBorder="false" v-model="baseFormData.title" placeholder="请输入房源标题" />
			</uni-forms-item>
			<!-- 发布房源 -->
			<view class="" v-if="publishstyle==0">
				<uni-forms-item name="price" label="期望售价:" required>
					<input  @blur="binddata('price', $event.detail.value)"  v-model="baseFormData.price" />
				</uni-forms-item>
				<uni-forms-item label="小区名称:" name="buildingName" required>
					<input  @blur="binddata('buildingName', $event.detail.value)"  v-model="baseFormData.buildingName" />
				</uni-forms-item>
				<uni-forms-item label="房屋面积:" name="area" required>
					<input  @blur="binddata('area', $event.detail.value)"  v-model="baseFormData.area" />
				</uni-forms-item>
				<uni-forms-item label="套内面积:" name="coverArea" required>
					<input  @blur="binddata('coverArea', $event.detail.value)" v-model="baseFormData.coverArea" />
				</uni-forms-item>
			</view>
			<!-- /发布房源 -->
			<!-- 发布租房 -->
			<view class="" v-if="publishstyle==1">
				<uni-forms-item label="租金:" name="price" required >
					<input  @blur="binddata('price', $event.detail.value)"  v-model="baseFormData.price" placeholder="元/月" />
				</uni-forms-item>
				<uni-forms-item label="出租方式:" name="category" required>
					<uni-data-checkbox  @blur="binddata('category', $event.detail.value)" v-model="baseFormData.category" :localdata="localRentalMethod"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item label="小区名称:" name="buildingName" required>
					<input  @blur="binddata('buildingName', $event.detail.value)" v-model="baseFormData.buildingName" />
				</uni-forms-item>
				<uni-forms-item label="房屋面积:" name="area" required>
					<input  @blur="binddata('area', $event.detail.value)" v-model="baseFormData.area" />
				</uni-forms-item>
			</view>
			<!-- /发布租房 -->
			
			<uni-forms-item label="户型:" name="type" required>
				<uni-data-select
        @blur="binddata('type', $event.detail.value)"
				class="selectlist"
				        v-model="baseFormData.type"
				        :localdata="localType"
				      ></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="楼层:" name="floor" required>
				<input  @blur="binddata('floor', $event.detail.value)" v-model.number="baseFormData.floor" />
			</uni-forms-item>
			<uni-forms-item label="总楼层:" name="floors" required>
				<input  @blur="binddata('floors', $event.detail.value)" v-model.number="baseFormData.floors" />
			</uni-forms-item>
			<uni-forms-item label="用途:" required>
				<uni-data-checkbox v-model="baseFormData.use" :localdata="localUse"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="朝向:" name="toward" >
				<input  @blur="binddata('toward', $event.detail.value)" v-model="baseFormData.toward" />
			</uni-forms-item>
			<uni-forms-item label="是否有电梯:" name="elevator" >
				<uni-data-checkbox v-model="baseFormData.elevator" :localdata="localLift"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="装修情况:" name="furnish" >
				<uni-data-checkbox v-model="baseFormData.furnish" :localdata="localSituation"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item label="上传图片" name="images" >
				<uni-file-picker v-model="imageValue" limit="9" @select="select" @progress="progress" @success="success" @fail="fail" @delete="deleteimg"  ></uni-file-picker>
			</uni-forms-item>
			
			<!-- 提交按钮 -->
			<button type="primary" class="subButton" @click="pubshInfo">发布房源</button>
		</uni-forms>
	</view>
</template>

<script>
  import COS from 'cos-wx-sdk-v5'
  import {mapState,mapActions,mapMutations} from 'vuex'

	export default {
		name:"publishform",
		props:{
			publishstyle:{
				type:Number,
				default:0,
			}
		},
    computed:{
      ...mapState('m_user',['token'])
      
    },
		data() {
			return {
				baseFormData: {
					title:'',
					status:1 ,
					area:'',
					price:'',
					type:null,
				  // coverArea:'',
          // 出租方式
          category:1,

					floor:null,
					use:null,
					toward:'',
					elevator:'',
					furnish:2,
				  images:[],
					buildingName:'',
					floors:null,
					contract:'',
					tel:''

				},
        rules:{
          title: {
            rules:[
              {required:true,
               errorMessage:'必填'
              },
              {
                  maxLength: 26,
                  errorMessage: '标题长度不能超过26个字'
              },
            ],
            
          },
          area: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          price: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          type: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          category: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          floor: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          use: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          furnish: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          toward: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          elevator: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          images: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          buildingName: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          floors: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          contract: {
            rules:[
              {required:true,
               errorMessage:'必填'
              }
            ],
            
          },
          tel: {
            rules:[
              {required:true,
               errorMessage:'必填'
              },
              {
                    validateFunction: function(rule, value, data, callback) {
                    const telReg = /^1[3456789]\d{9}$/
                    if (telReg.test(value)) {
                          return true
                      } else {
                          callback('手机号格式有误')
                      }
                  }
              }
            //   {
            //     minLength: 11,
            //     maxLength: 11,
            //     errorMessage: '账号长度为11位'
            // },
           
            ],
            
          }
          
        },
        imageValue:[],
				localType:[
					{ value: 1, text: "一室一厅" },
					{ value: 2, text: "两室一厅" },
					{ value: 3, text: "三室一厅" },
					{ value: 4, text: "四室两厅" },
					{ value: 5, text: "五室两厅" },
				],
				localUse:[
					{text:'普通住宅',value:1},
					{text:'公寓',value:2},
				],
				localLift:[
					{text:'是',value:true},
					{text:'否',value:false},
				],
				localSituation:[
					{text:'清水',value:1},
					{text:'精装',value:2},
				],
				localRentalMethod:[
					{text:'整租',value:1},
					{text:'合租',value:2},
				],
			};
		},
		methods:{
      pubshInfo() {
        // console.log(1)
        if(this.token) {
          this.$refs.baseForm.validate().then(async success=>{
          				// console.log('表单数据信息：', res);
                const res =  await uni.$http.post('/user/rental/add',this.baseFormData)
                if(res.data.msg === 'ok') {
                  // 发布成功
                  this.baseFormData = {
                                  title:'',
                                  status:1 ,
                                  area:'',
                                  price:'',
                                  type:null,
                                  // coverArea:'',
                                  category:1,
                                  floor:null,
                                  use:null,
                                  toward:'',
                                  elevator:'',
                                  furnish:2,
                                  images:[],
                                  buildingName:'',
                                  floors:null,
                                  contract:'',
                                  tel:''
                                }
                  this.$refs.baseForm.clearValidate()
                this.imageValue = []
                uni.showToast({
                  title:'发布成功，请等待后台审核',
                  duration:2000,
                  mask:true
                })
                }
                  
          			}).catch(err =>{
          				console.log('表单错误信息：', err);
                  uni.showToast({
                    title:'信息填写有误，请核对后再发布',
                    icon:'none',
                    duration:2000,
                    mask:true
                  })
          			})
        }else {
          // 没有登录，回到登录页登录数据回显
          this.$store.dispatch('m_nav/delayNavigate')
          this.$store.commit('m_pub/setFormData',this.baseFormData)
          this.$store.commit('m_path/setPath',{
                      type:'switchTab',
                      url:'/pages/publish/publish'
                      
    })
        }
        
      },
			// 获取上传状态
			select(e){
				console.log('选择文件：',e)
        var that = this
        const cos = new COS({
          SecretId: 'AKIDYzPfswoV3QabTCinsvWwHYcXI5oRxQmy', // 获取的密钥id
          SecretKey: '4wjMo5KSP9i7NUUOPFtMbxELH0ZzEHKH', // 获取的密钥key
        })
        // console.log('选中',e)
        var filePathList = e.tempFilePaths
        filePathList.forEach((item, index) => {
        						const pathName = that.getRandomString() + '.png'
         
        						// 微信小程序
        						cos.uploadFile({ //putObject
        								Bucket: 'starnest-image-1318859073', // 填入您自己的存储桶，必须字段
        								Region: 'ap-chengdu', // 存储桶所在地域，例如ap-beijing，必须字段
        								Key: pathName, // 上传的cos时，起一个别名
        								FilePath: item, // 要上传的文件
        								SliceSize: 1024 * 1024 * 5, // 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须
        							},
        							function(err, data) {
        								// console.log(index, err || data)
                //         console.log(data.headers,'headers....')
                        // console.log(data.location,'location....')
        								if (err) return
        								that.imageValue.push({
        									url: data.headers.location,
        									name: pathName
        								})
                        that.baseFormData.images.push(data.headers.location[0])
                        // console.log(that.imageValue)
                        console.log(that.baseFormData.images,'上传后端')
        							})
         
        					})
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功')
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
        uni.showToast({
          title:'图片上传失败！',
          icon:'error',
          duration:2000,
          mask:true
        })
			},
			// 删除触发
			deleteimg(e){
        // console.log(e.tempFile.path[0],'删除的e')
      this.baseFormData.images = this.baseFormData.images.filter(item => item !== e.tempFile.path[0])
        const delkey = e.tempFile.name
        					const cos = new COS({
        						SecretId: 'AKIDYzPfswoV3QabTCinsvWwHYcXI5oRxQmy', // 获取的密钥id
        						SecretKey: '4wjMo5KSP9i7NUUOPFtMbxELH0ZzEHKH', // 获取的密钥key
        					});
        					// 删除操作
        					cos.deleteObject({
        						Bucket: 'starnest-image-1318859073', // 填入您自己的存储桶，必须字段
        						Region: 'ap-chengdu', // 存储桶所在地域，例如ap-beijing，必须字段
        						Key: delkey, // 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段
        					}, function(err, data) {
        						console.log(err || data);
        					});
			},
      getRandomString(len) {
      				let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
      					min = 0,
      					max = _charStr.length - 1,
      					_str = ''; //定义随机字符串 变量
      				//判断是否指定长度，否则默认长度为15
      				len = len || 15;
      				//循环生成字符串
      				for (var i = 0, index; i < len; i++) {
      					index = (function(randomIndexFunc, i) {
      						return randomIndexFunc(min, max, i, randomIndexFunc);
      					})(function(min, max, i, _self) {
      						let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
      							numStart = _charStr.length - 10;
      						if (i == 0 && indexTemp >= numStart) {
      							indexTemp = _self(min, max, i, _self);
      						}
      						return indexTemp;
      					}, i);
      					_str += _charStr[index];
      				}
      				return _str;
      			},
      // 发布房源
      // pubshInfo() {
        
      // }
		},
    onReady() {
    		// 需要在onReady中设置规则
    		this.$refs.baseForm.setRules(this.rules)
    	},
	}
</script>

<style lang="scss" scoped>
	.formcontent{
		background: #fff;
		padding-bottom: 100rpx;
		.subButton{
			position: fixed;
			width: 90%;
			background-color:#2bbbef;
			bottom: 0;
			left: 50%;
			transform: translate(-50%,0);
		}
		#deep .uni-easyinput__content-input{
			background: whitesmoke !important;
		}
		.selectlist{
			width: 70%;
		}
	}
</style>